<script setup lang="tsx">
import { ref, computed, PropType } from 'vue'
import { useDictStore } from '@/store/modules/dictData'
import { FloorChart } from '@/api/securcheck/type'
const DictStore = useDictStore()
DictStore.setDict('secur_enthm_state') //入户状态
DictStore.setDict('secur_user_state') //用户状态
const props = defineProps({
  currentRow: {
    type: Object as PropType<FloorChart[]>,
    default: () => null
  }
})
const Title = ref('')
// 原始数据
// 获取所有楼层
const getAllFloors = (residents: any) => {
  return [...new Set(residents.map((resident) => resident.floorLevel))] as string[]
}
// 获取所有单元
const getAllUnits = (residents: any) => {
  return [...new Set(residents.map((resident) => resident.unitNo))] as string[]
}
// 生成模拟数据
props.currentRow.map((item) => {
  item['floorLevel'] = item.roomNo.substring(0, 2)
})

const allResidents = ref<FloorChart[]>(props.currentRow)
const searchQuery = ref<string>('')
const filterStatus = ref<string>('')
const selectedRoom = ref<FloorChart | null>(null)
const units: string[] = getAllUnits(allResidents.value)
const floors: string[] = getAllFloors(allResidents.value).reverse()
if (allResidents.value.length !== 0) {
  Title.value = `${allResidents.value[0].community}${allResidents.value[0].floorNo}号楼（共计${allResidents.value.length}户）`
}
// 计算属性
const filteredResidents = computed(() => {
  let filtered = allResidents.value
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(
      (room) =>
        room.contacts?.toLowerCase().includes(query) ||
        room.roomNo?.includes(query) ||
        `${room.unitNo}-${room.roomNo}`.includes(query)
    )
  }

  if (filterStatus.value === 'occupied') {
    filtered = filtered.filter((room) => room.contacts)
  } else if (filterStatus.value === 'vacant') {
    filtered = filtered.filter((room) => !room.contacts)
  }

  return filtered
})

const filteredUnits: any = computed(() => {
  return units.filter((unit) => {
    return filteredResidents.value.some((room) => room.unitNo === unit)
  })
})

// 方法
const getRoomsByLocation = (unit: string, floor: string): FloorChart[] => {
  return filteredResidents.value.filter((room) => room.unitNo === unit && room.floorLevel === floor)
}
const showDetails = (room: FloorChart) => {
  selectedRoom.value = room
}

const getStatusClass = (room: FloorChart): string => {
  if (!room.enthmState) return ''
  const i = ref('')
  DictStore.$state.secur_enthm_state?.map((item) => {
    if (item.dictValue == room.enthmState) {
      i.value = item.listClass
      return item.dictLabel
    }
  })
  return i.value
}
const getUserClass = (room: FloorChart): string => {
  if (!room.enthmState) return ''
  const i = ref('')
  DictStore.$state.secur_user_state?.map((item) => {
    if (item.dictValue == room.userState) {
      i.value = item.listClass
      return item.dictLabel
    }
  })
  return `room${i.value}`
}
const getStatusText = (state: string | undefined, type: string): string => {
  const i = ref('')
  if (type == 'UserState') {
    DictStore.$state.secur_user_state?.map((item) => {
      if (item.dictValue == state) {
        i.value = item.dictLabel
        return item.dictLabel
      }
    })
  } else {
    DictStore.$state.secur_enthm_state?.map((item) => {
      if (item.dictValue == state) {
        i.value = item.dictLabel
        return item.dictLabel
      }
    })
  }
  return i.value
}

const closeModal = () => {
  selectedRoom.value = null
}
</script>

<template>
  <div class="building-system">
    <div class="dashboard">
      <h3 style="text-align: center">{{ Title }}</h3>
      <div class="legend">
        <div class="legend-item" v-for="item in DictStore.$state.secur_user_state" :key="item.dictValue">
          <div class="legend-color" :class="'room' + item.listClass"></div>
          <span>{{ item.dictLabel }}</span>
        </div>
        <div class="legend-item" v-for="item in DictStore.$state.secur_enthm_state" :key="item.dictValue">
          <div :class="item.listClass" class="room-statu"></div>
          <span>{{ item.dictLabel }}</span>
        </div>
      </div>
      <!-- <div class="sidebar">
        <div class="filters">
          <h3 class="filter-title"><i class="fas fa-filter"></i> 筛选条件</h3>
          <div class="search-box">
            <i class="fas fa-search"></i>
            <input
              type="text"
              placeholder="搜索住户姓名或房间号..."
              v-model="searchQuery"
            />
          </div>

          <div class="tabs">
            <div
              :class="['tab', filterStatus === '' ? 'active' : '']"
              @click="filterStatus = ''"
            >
              全部
            </div>
            <div
              :class="['tab', filterStatus === 'occupied' ? 'active' : '']"
              @click="filterStatus = 'occupied'"
            >
              已入住
            </div>
            <div
              :class="['tab', filterStatus === 'vacant' ? 'active' : '']"
              @click="filterStatus = 'vacant'"
            >
              未入住
            </div>
          </div>
        </div>

        <div class="stats">
          <div class="stat-card">
            <div class="stat-value">{{ totalRooms }}</div>
            <div class="stat-label">总房间数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ occupiedRooms }}</div>
            <div class="stat-label">已入住</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ vacantRooms }}</div>
            <div class="stat-label">未入住</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ units.length }}</div>
            <div class="stat-label">单元数</div>
          </div>
        </div>
      </div> -->

      <div class="building-container">
        <div class="building-layout">
          <div class="unit" v-for="unit in filteredUnits" :key="unit">
            <div class="unit-header">{{ unit }}单元</div>
            <div class="floors">
              <div class="floor" v-for="floor in floors" :key="floor">
                <div class="floor-label">{{ floor }}层</div>
                <div class="rooms">
                  <div
                    v-for="room in getRoomsByLocation(unit, floor)"
                    :key="room.uuid"
                    class="room"
                    :class="getUserClass(room)"
                    @click="showDetails(room)"
                  >
                    <div class="room-status" :class="getStatusClass(room)"></div>
                    <div class="room-number">{{ room.roomNo.slice(1) }}</div>
                    <div class="room-owner">{{ room.contacts || '空置' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <div class="modal-mask" v-if="selectedRoom" @click.self="closeModal">
      <div class="modal-container">
        <div class="modal-header">
          <h2 class="modal-title">住户详情</h2>
          <button class="close-button" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body" v-if="selectedRoom">
          <div class="detail-grid">
            <div class="detail-label">房间号：</div>
            <div class="detail-value"> {{ selectedRoom.unitNo }}-{{ selectedRoom.roomNo }} </div>

            <div class="detail-label">住户姓名：</div>
            <div class="detail-value">{{ selectedRoom.contacts || '未入住' }}</div>

            <div class="detail-label">联系电话：</div>
            <div class="detail-value">{{ selectedRoom.contPhone || '-' }}</div>

            <div class="detail-label">用户状态：</div>
            <div class="detail-value">
              {{ getStatusText(selectedRoom.userState, 'UserState') }}
            </div>

            <div class="detail-label">入户状态：</div>
            <div class="detail-value">
              {{ getStatusText(selectedRoom.enthmState, 'enthmState') }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.building-system {
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  background: linear-gradient(120deg, #3498db, #2c3e50);
  color: white;
  padding: 25px;
  border-radius: 12px;
  margin-bottom: 25px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  text-align: center;
}

.header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.dashboard {
  display: grid;
  /* grid-template-columns: 300px 1fr; */
  gap: 25px;
}

.sidebar {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.filters {
  margin-bottom: 25px;
}

.filter-title {
  font-size: 1.2rem;
  margin-bottom: 15px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-box input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s;
}

.search-box input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.search-box i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7f8c8d;
}

.tabs {
  display: flex;
  gap: 5px;
  margin-bottom: 25px;
  background: #f8f9fa;
  padding: 5px;
  border-radius: 8px;
}

.tab {
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.tab.active {
  background: #3498db;
  color: white;
}

.stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  margin-top: 20px;
}

.stat-card {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  border-left: 4px solid #3498db;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #2c3e50;
}

.stat-label {
  font-size: 0.9rem;
  color: #7f8c8d;
}

.building-container {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.building-layout {
  display: flex;
  gap: 30px;
  justify-content: center;
}

.unit {
  min-width: 300px;
}

.unit-header {
  background: #2c3e50;
  color: white;
  text-align: center;
  padding: 15px;
  font-size: 1.2rem;
  font-weight: 500;
  border-radius: 8px 8px 0 0;
}

.floors {
  border: 1px solid #e0e0e0;
  border-top: none;
  border-radius: 0 0 8px 8px;
  overflow: hidden;
}

.floor {
  display: flex;
  border-bottom: 1px solid #eee;
  background: white;
  transition: background 0.3s;
}

.floor:hover {
  background: #f8f9fa;
}

.floor:last-child {
  border-bottom: none;
}

.floor-label {
  width: 60px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  font-weight: bold;
  color: #555;
  border-right: 1px solid #eee;
}

.rooms {
  display: flex;
  flex-wrap: wrap;
  padding: 15px;
  gap: 15px;
  flex: 1;
}

.room {
  width: 80px;
  height: 80px;
  border: 2px solid #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.roomprimary {
  background: linear-gradient(135deg, #d5f5e3 0%, #abebc6 100%);
  border-color: #2ecc71;
}

.roomwarning {
  background: linear-gradient(135deg, #d9e0e8c5 0%, #e9ecef 100%);
  border-color: #dfe3e6ed;
}
.roomdanger {
  background: linear-gradient(135deg, #d3181874 0%, #e9362271 100%);
  border-color: #e74c3c;
}
.room-number {
  font-weight: bold;
  margin-bottom: 5px;
  color: #2c3e50;
}

.room-owner {
  font-size: 0.8rem;
  color: #555;
  text-align: center;
  padding: 0 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.room:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.room-status {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.room-statu {
  position: absolute;
  left: -2px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.primary {
  background-color: #2ecc71;
}

.warning {
  background-color: #f39c12;
}
.info {
  background-color: rgb(177, 179, 184);
}
.danger {
  background-color: #e74c3c;
}

.legend {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

.legend-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 15px;
  background: #f8f9fa;
  border-radius: 20px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.occupied-color {
  background: linear-gradient(135deg, #d5f5e3 0%, #abebc6 100%);
  border: 2px solid #2ecc71;
}

.vacant-color {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 2px solid #ddd;
}

.modal-mask {
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.modal-container {
  width: 500px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.modal-header {
  padding: 20px;
  background: linear-gradient(120deg, #3498db, #2c3e50);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 1.5rem;
  font-weight: 500;
}

.close-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
}

.modal-body {
  padding: 25px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 15px;
}

.detail-label {
  font-weight: bold;
  color: #7f8c8d;
  text-align: right;
}

.detail-value {
  color: #2c3e50;
}

.status-badge-normal {
  background-color: #d5f5e3;
  color: #27ae60;
}

.status-badge-warning {
  background-color: #fef5e7;
  color: #f39c12;
}

.status-badge-alert {
  background-color: #fdedec;
  color: #e74c3c;
}

@media (max-width: 900px) {
  .dashboard {
    grid-template-columns: 1fr;
  }
  .building-layout {
    flex-direction: column;
    align-items: center;
  }
  .unit {
    width: 100%;
  }
}
</style>
